package com.vgooo.client.index;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.NewListInfo;
import com.vgooo.bean.ProdAbstract;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.mobile.MobileAdapter;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.Loading;
import com.vgooo.util.Loading.Progress;
import com.vgooo.util.UmengUtils;
import com.vgooo.util.Utils;

public class IndexSearchActivity extends VGActivity{
	
	
	

	private final static String className = "IndexSearchActivity";// 类名，用于调试
	

	private EditText search;// 搜索框
	private String keyWord ;//搜索关键词
	

	private TextView noResult ;
	private GridView mobiesList;// 首页搜索热门手机推荐
	private List<ProdAbstract> prodsInfo;// 热门推荐手机列表
	private MobileAdapter mobileAdapter;// 热门推荐手机适配器

	
	private Context context = this ;

	@Override
	public void setupView() {
		//隐藏键盘
		Utils.hideSoftInput(search);
		progress.cancel() ;
		// 首页热门机型推荐
		mobileAdapter = new MobileAdapter(prodsInfo, this);
		mobiesList.setAdapter(mobileAdapter);
		if(null==prodsInfo||prodsInfo.isEmpty()||prodsInfo.size()<1){
			noResult.setVisibility(View.VISIBLE);
		}else{
			noResult.setVisibility(View.GONE);
		}

	}

	/**
	 * 添加监听事件
	 */
	@Override
	public void addListener() {
		// 手机列表监听事件
		mobiesList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				
				
				ProdAbstract prod = (ProdAbstract) mobileAdapter
						.getItem(position);

				log("prod = " + prod);
				if(prod.isBlank){
					return ;
				}
				StringBuffer link = new StringBuffer("proddetail?");
				link.append("b=").append(prod.brand_html).append("&p=")
						.append(prod.prod_html);
				log("link = " + link);

				Main.moblieDetailIntent.putExtra("link", link.toString());
				ViewLayout.setViewPre(true, "手机详情", ViewLayout.TAB_TAG_MOBILE_DETAIL,cparent);
				
			}
		});
		
		search.setOnKeyListener(new MyOnKeyClickListener());
	}

	/**
	 * 打印调试信息
	 * 
	 * @param info
	 */
	private void log(String info) {
		Log.i(this.getClass().getSimpleName(), info);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index_search);
		initView();
		addListener();
	}

	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode==KeyEvent.KEYCODE_ENTER){
			DebugTools.toast(context, "KEYCODE_ENTER") ;
//			new DataSAsyncLoader(cparent).execute(null);
			init() ;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
		//隐藏键盘
		Utils.hideSoftInput(search);
	}
	
	@Override
	public void initView() {
		// TODO Auto-generated method stub
		search = (EditText) findViewById(R.id.index_search_box_tv);

		mobiesList = (GridView) findViewById(R.id.index_search_gridView);
		
		noResult = (TextView) findViewById(R.id.index_search_no_result);
		noResult.setVisibility(View.GONE);


	}

	@Override
	public void flashView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void getData(){
		try {
			search();
//		setupView();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e) ;
		}
	}

	/**
	 * 搜索
	 * @throws Exception 
	 */
	private void search() throws Exception {
		keyWord = search.getText().toString().trim();
		if ("".equals(keyWord) || keyWord == null) {
			search.setError("请输入手机品牌或型号");
			search.isFocused();
			return;
		}
		keyWord = URLEncoder.encode(keyWord);
		
		// 搜索产品
		String urlPath = HttpUtils.BASE_URI + "search?type=prod&kw=" + keyWord;
		String jsonString = HttpUtils.getJsonString(urlPath);
		if (jsonString.equals("") || jsonString == null) {
			DebugTools.toast(this, "未找到相关产品。。。");
			return;
		}
		Map<String, Object> m1 = GSonTools.getObjectMaps(jsonString);
		Map<String, Object> m2 = (Map<String, Object>) m1.get("prods");
		List<Map<String, Object>> list = (List<Map<String, Object>>) m2
				.get("prods");
		prodsInfo = new ArrayList<ProdAbstract>(
				list.size());
		for (Map<String, Object> map : list) {
			ProdAbstract prod = new ProdAbstract();
			prod.brand_html = (String) map.get("brand_html");
			prod.brand_name = (String) map.get("brand_name");
			prod.prod_html = (String) map.get("prod_html");
			prod.prod_name = (String) map.get("prod_name");
			prod.prod_thumbnail = (String) map.get("prod_thumbnail");
			prod.price_sell = (String) map.get("lower_price");
			prodsInfo.add(prod);
		}
		ProdAbstract prod = new ProdAbstract();
		prod.isBlank = true ;
		if(!prodsInfo.isEmpty()){
			while (prodsInfo.size()%3!=0) {
				prodsInfo.add(prod);
			}
			
		}
		
		DebugTools.log(className, "prodsSearchInfo = " + prodsInfo);

		
	}

	

	
	private class MyOnKeyClickListener implements OnKeyListener{

		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			if(keyCode==KeyEvent.KEYCODE_ENTER){
				init() ;
			}
			return false;
		}
		
	}
	
	
	
}